package site.xuxingcan.autodownload;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/9/24.
 */
public class AuthUtil {
    public static boolean isAuthOk = false;

    public static boolean Auth() {
        try {
            AVQuery<AVObject> query = new AVQuery<>("authorization");
            query.whereEqualTo("WID", WID.getImeiMd5(MyApplication.mContext));
            List<AVObject> list = query.find();
            long currentTime = getWebsiteDatetime("http://www.baidu.com");
            if (list.size() != 0) {
                AVObject avObject = list.get(0);
                Date date = avObject.getDate("DATE");
                if (currentTime < date.getTime()) {
                    isAuthOk = true;
                    return true;
                }
            } else {
                query = new AVQuery<>("authorization");
                query.whereEqualTo("WID", WID.getWid());
                list = query.find();
                if (list.size() != 0) {
                    AVObject avObject = list.get(0);
                    Date date = avObject.getDate("DATE");
                    if (currentTime < date.getTime()) {
                        isAuthOk = true;
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isAuthOk = false;
        return false;
    }

    private static long getWebsiteDatetime(String webUrl) {
        try {
            URL url = new URL(webUrl);// 取得资源对象
            URLConnection uc = url.openConnection();// 生成连接对象
            uc.connect();// 发出连接
            long ld = uc.getDate();// 读取网站日期时间
//            Date date = new Date(ld);// 转换为标准时间对象
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
            return ld;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Long.MAX_VALUE;
    }
}
